
import { _decorator, Component, Node, sys } from 'cc';
import EvtManger from '../tools/EvtManger';
import { AppControll, configKey, ConfigKey, EventName, secretShop_config } from '../manager/AppControll';
import { SoundManager } from '../manager/SoundManger';
import { DataHelper } from './DataHelper';
import { levelData } from '../pop/Rank';
const { ccclass, property } = _decorator;


export type SecondaryGunStruct = {
    configId: number;
    level: number;
}

export enum PhaseTransitionType {
    lock = 1,
    automatic = 2,
}

export type SkinFragment = {
    skinId: number;
    count: number
}

export type PlayerData =
    {
        IsNewPlayer: boolean;
        KillMonsters: number,
        MGAttackLv: number,
        MGCriticalHitRateLv: number,
        MGCriticalHitDamageLv: number,
        MGDamageBoostLv: number,
        MGAutomaticAttackLv: number
        Gold: number,
        Honor: number,
        UnLockSecondaryGun: number[];
        SecondaryGun: SecondaryGunStruct[];
        CurStage: number,
        PhaseTransition: PhaseTransitionType,
        musicSwitch: boolean,
        effectSwitch: boolean,
        vibrate: boolean,
        time: string,
        firstTime: string;
        skin: number[],
        skinFragments: SkinFragment[],
        curGunSkinId: number,
        lastSigninTime: number,
        signInCount: number,
        curSignIn: number,
        freeRandomCount: number,
        secondGuide: boolean,
        challengeCount: number,
        adChallengeCount: number
        lastTime: number,
        turntableFreeTimes: number,
        turntableVideoTimes: number,
        blueStuff: number,
        purpleStuff: number,
        yellowStuff: number,
        redStuff: number,
        secretShopFreeTimes: number,
        secretShopVideoTimes: number,
        secretShopReward: number[]
        pearls: number,
        randomLevel: number,
        upgradeTime: number,
        upgradeTotal: number,
        craftingTableLv: number,
        giftGuide: boolean,
        tasteGuide: boolean,
        singnGuide: boolean,
        mainGuide: boolean,
        stageGuide: boolean,
    }

@ccclass('GameData')
export class GameData {
    static giftTime = 10;
    static buffDuration = 20;
    static bossTime = 10;
    static playerData: PlayerData = null;
    static giftDmg = 0; //计算是为(1+giftDmg) 所以实际数值为3
    static giftGold = 1;
    static backgroundPath = "bg/"
    static localKey = "first";
    static mainGunlevelUpAn: string = "mainGunLevelUp"
    static secondGunlevelUpAn: string = "secondGunLevelUp"
    static btnClick: string = "ui/click"
    static getRandom: string = "ui/choujiang"
    static openId: string = null;
    static userInfo: any = null;
    static updateRankTime = 500;
    static myLevelData: levelData = null;
    static productPool: secretShop_config[] = [];
    static mRes = {
        1: "reward_month_icon_gold",
        3: "blueStuff",
        4: "purpleStuff",
        5: "yellowStuff",
        6: "redStuff",
        7: "manyPearls_icon"
    }

    static defaultData: PlayerData = {
        IsNewPlayer: true,  //是否是新玩家
        KillMonsters: 0,    //击杀怪物数
        MGAttackLv: 1,
        MGCriticalHitRateLv: 1,
        MGCriticalHitDamageLv: 1,
        MGAutomaticAttackLv: 0,
        MGDamageBoostLv: 1,
        Gold: 0,
        UnLockSecondaryGun: [],
        SecondaryGun: [],
        CurStage: 10001,
        PhaseTransition: PhaseTransitionType.automatic,
        Honor: 0,
        skin: [110001],
        musicSwitch: true,
        effectSwitch: true,
        vibrate: true,
        time: null,
        firstTime: null,
        skinFragments: [],
        curGunSkinId: 110001,
        lastSigninTime: null,
        signInCount: 0,
        curSignIn: 1,
        freeRandomCount: 3,
        secondGuide: true,
        giftGuide: true,
        tasteGuide: true,
        singnGuide: true,
        mainGuide: true,
        stageGuide: true,
        challengeCount: 0,
        adChallengeCount: 0,
        lastTime: null,
        turntableFreeTimes: null,
        turntableVideoTimes: null,
        blueStuff: 200,
        purpleStuff: 60,
        yellowStuff: 20,
        redStuff: 10,
        secretShopFreeTimes: null,
        secretShopVideoTimes: null,
        secretShopReward: null,
        pearls: 0,
        randomLevel: 0,
        upgradeTime: null,
        upgradeTotal: null,
        craftingTableLv: 0
    }
    static curToastTotalTime: number = null;
    static isPause: boolean = false;
    static TasteInitial: number = 90001;

    start() {
        // [3]
    }

    static InitPlayData() {
        let tempStr = sys.localStorage.getItem(GameData.localKey);
        if (tempStr) {
            GameData.playerData = JSON.parse(tempStr);
        } else {
            GameData.playerData = GameData.defaultData;
        }
        if (!GameData.playerData.skin) {
            GameData.playerData.skin = [110001];
            GameData.playerData.skinFragments = [];
            GameData.playerData.curGunSkinId = 110001;
        }
        if (GameData.playerData.curSignIn == null || GameData.playerData.curSignIn == undefined) {
            GameData.playerData.curSignIn = 1;
            GameData.playerData.signInCount = 0;
        }
        if (GameData.playerData.lastSigninTime == null) {
            GameData.playerData.lastSigninTime = Date.now()
        }
        this.RecordTime();
        for (const key in GameData.defaultData) {
            if (Object.prototype.hasOwnProperty.call(GameData.defaultData, key)) {
                console.log(key);
                const element = GameData.playerData[key];
                if (element === undefined) {
                    GameData.playerData[key] = GameData.defaultData[key];
                }
            }
        }
    }

    static SetGiftGold(n: number) {
        this.giftGold = n;
    }

    static SetGiftDmg(n: number) {
        this.giftDmg = n - 1;
    }


    static UnlockdaryGun(id: number) {
        if (this.playerData.UnLockSecondaryGun.indexOf(id) == -1) {
            this.playerData.UnLockSecondaryGun.push(id);
            this.playerData.SecondaryGun.push(null);
        }
    }

    static SetSecondaryGunByUnlockId(id: number, st: SecondaryGunStruct) {
        let index = this.playerData.UnLockSecondaryGun.indexOf(id);
        if (index != -1) {
            this.playerData.SecondaryGun[index] = st;
        }
    }

    static GetSecondaryGunByUnlockId(id: number): SecondaryGunStruct {
        let index = this.playerData.UnLockSecondaryGun.indexOf(id);
        if (index != -1) {
            return this.playerData.SecondaryGun[index];
        } else {
            return null;
        }
    }

    static GetGiftGoldReward(): number {
        return DataHelper.GetMonsterRefreshByAuto().LimitedTimeAwardGold;
    }

    /**
     * 
     * @param num 
     * @param isSpeacial 为True时不参与加倍
     */
    static AddGold(num: number, isSpeacial: boolean = false) {
        let add = num;
        if (num >= 0 && !isSpeacial) {
            add *= this.giftGold;
        }
        GameData.playerData.Gold += add;
        EvtManger.do(EventName.addGold, add);
        this.SavePlayData();
    }

    static AddPearls(num: number) {
        if (GameData.playerData.pearls == undefined) {
            GameData.playerData.pearls = 0;
        }
        GameData.playerData.pearls += num;
        EvtManger.do(EventName.updatePearls);
        this.SavePlayData();
    }

    static AddHonor(num: number) {
        GameData.playerData.Honor += num;
        EvtManger.do(EventName.addHonor, num);
        if (GameData.playerData.MGAutomaticAttackLv == 0 && GameData.playerData.Honor >= Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.autoAtkUnlock).value)) {
            AppControll.Platform.SendBuryPoint(100014);
            GameData.playerData.MGAutomaticAttackLv = 1;
            EvtManger.do(EventName.automaticUpgrade);
        }
        this.SavePlayData();
        this.RecordTime();
    }

    static SavePlayData() {
        GameData.playerData.challengeCount = GameData.GetCurlevelChallengeFreeTimes();
        GameData.playerData.adChallengeCount = GameData.GetCurlevelChallengeAdTimes();
        GameData.playerData.turntableFreeTimes = GameData.GetTurnFreeTimes();
        GameData.playerData.turntableVideoTimes = GameData.GetTurnADTimes();
        GameData.playerData.lastTime = Date.now();
        sys.localStorage.setItem(GameData.localKey, JSON.stringify(this.playerData));
    }

    static RecordTime() {
        const now = new Date();
        if (this.playerData.firstTime == null) {
            this.playerData.firstTime = now.toISOString();
        }
        this.playerData.time = now.toISOString();
    }

    static GetCurSignIn() {
        let currentTime = Date.now()
        let consecutiveDays = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.signInReset).value);
        let lastTime = GameData.playerData.lastSigninTime;
        let result = GameData.playerData.curSignIn;
        if (GameData.playerData.signInCount == undefined) {
            GameData.playerData.signInCount = 0;
        }

        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay - lastSigninDay < consecutiveDays && currentDay > lastSigninDay) {
                result = GameData.playerData.curSignIn + 1;
                GameData.playerData.signInCount = 0;
            } else if (currentMonth - lastSigninMonth == 1 && (this.getDaysInMonth(lastSigninYear, lastSigninMonth) - lastSigninDay + currentDay) < consecutiveDays) {
                result = GameData.playerData.curSignIn + 1;
                GameData.playerData.signInCount = 0;
            } else if (currentMonth === lastSigninMonth && currentDay - lastSigninDay >= consecutiveDays) {
                GameData.playerData.signInCount = 0;
                result = 1;
            } else if (currentMonth - lastSigninMonth == 1 && (this.getDaysInMonth(lastSigninYear, lastSigninMonth) - lastSigninDay + currentDay) >= consecutiveDays) {
                GameData.playerData.signInCount = 0;
                result = 1;
            } else if (currentMonth - lastSigninMonth > 1) {
                GameData.playerData.signInCount = 0;
                result = 1;
            }
        }
        if (result == 8) {
            result = 1;
        }
        return result;
    }

    static GetCurlevelChallengeFreeTimes(): number {
        let currentTime = Date.now()
        let levelChallengeFreeTimes = GameData.playerData.challengeCount;
        let lastTime = GameData.playerData.lastTime;
        if (GameData.playerData.lastTime == null || GameData.playerData.lastTime == undefined) {
            return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.levelChallengeFreeTimes).value);
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return levelChallengeFreeTimes;
            } else {
                return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.levelChallengeFreeTimes).value);
            }
        }
    }

    static GetCurlevelChallengeAdTimes(): number {
        let currentTime = Date.now()
        let adlevelChallengeFreeTimes = GameData.playerData.adChallengeCount;
        let lastTime = GameData.playerData.lastTime;
        if (GameData.playerData.lastTime == null || GameData.playerData.lastTime == undefined) {
            return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.levelChallengeVideoTimes).value);
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return adlevelChallengeFreeTimes;
            } else {
                return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.levelChallengeVideoTimes).value);
            }
        }
    }

    static GetTurnFreeTimes() {
        let currentTime = Date.now()
        let TurnFreeTimes = GameData.playerData.turntableFreeTimes;
        let lastTime = GameData.playerData.lastTime;
        if (GameData.playerData.turntableFreeTimes == null || GameData.playerData.turntableFreeTimes == undefined || lastTime == null || lastTime == undefined) {
            return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.turntableFreeTimes).value);
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return TurnFreeTimes;
            } else {
                return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.turntableFreeTimes).value);
            }
        }
    }

    static GetTurnADTimes() {
        let currentTime = Date.now()
        let TurnFreeTimes = GameData.playerData.turntableVideoTimes;
        let lastTime = GameData.playerData.lastTime;
        if (GameData.playerData.turntableFreeTimes == null || GameData.playerData.turntableFreeTimes == undefined || lastTime == null || lastTime == undefined) {
            return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.turntableFreeTimes).value);
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return TurnFreeTimes;
            } else {
                return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.turntableVideoTimes).value);
            }
        }
    }

    static GetSecretShopVideoTimes() {
        let currentTime = Date.now()
        let TurnFreeTimes = GameData.playerData.secretShopVideoTimes;
        let lastTime = GameData.playerData.lastTime;
        if (GameData.playerData.secretShopVideoTimes == null || GameData.playerData.secretShopVideoTimes == undefined || lastTime == null || lastTime == undefined) {
            return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.secretShopFreeTimes).value);
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return TurnFreeTimes;
            } else {
                return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.secretShopVideoTimes).value);
            }
        }
    }

    static GetSecretShopFreeTimes() {
        let currentTime = Date.now()
        let TurnFreeTimes = GameData.playerData.secretShopFreeTimes;
        let lastTime = GameData.playerData.lastTime;
        if (GameData.playerData.secretShopFreeTimes == null || GameData.playerData.secretShopFreeTimes == undefined || lastTime == null || lastTime == undefined) {
            return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.secretShopFreeTimes).value);
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return TurnFreeTimes;
            } else {
                return Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.secretShopFreeTimes).value);
            }
        }
    }

    static GetSecretShopLt() {
        let currentTime = Date.now()
        let rewards = GameData.playerData.secretShopReward;
        let lastTime = GameData.playerData.lastTime;
        if (lastTime == null || lastTime == undefined || !rewards) {
            return GameData.GetGoods()
        }
        const currentDate = new Date(currentTime);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();

        // 获取上次签到日期的年月日
        const lastSigninDate = new Date(lastTime);
        const lastSigninYear = lastSigninDate.getFullYear();
        const lastSigninMonth = lastSigninDate.getMonth() + 1;
        const lastSigninDay = lastSigninDate.getDate();

        if (currentYear === lastSigninYear) {
            if (currentMonth === lastSigninMonth && currentDay === lastSigninDay) {
                return rewards;
            } else {
                return GameData.GetGoods();
            }
        }

    }

    static getDaysInMonth(year: number, month: number): number {
        return new Date(year, month, 0).getDate();
    }

    static InitSecretShop() {
        let config = DataHelper.GetSecretShopConfig();
        for (const key in config) {
            if (Object.prototype.hasOwnProperty.call(config, key)) {
                const element = config[key];
                this.productPool.push(element);
            }
        }
    }

    static GetGoods(): number[] {
        //根据权重随机3个商品
        let selectedProducts = [];
        let totalWeight = GameData.productPool.reduce((sum, product) => sum + product.rewardWeight, 0);

        while (selectedProducts.length < 3) {
            let randomWeight = Math.random() * totalWeight;
            let cumulativeWeight = 0;

            for (let i = 0; i < GameData.productPool.length; i++) {
                cumulativeWeight += GameData.productPool[i].rewardWeight;

                if (randomWeight <= cumulativeWeight) {
                    selectedProducts.push(GameData.productPool[i].shopId);
                    break;
                }
            }
        }
        return selectedProducts;
    }

    static UpdateData() {
        GameData.playerData.challengeCount = GameData.GetCurlevelChallengeFreeTimes();
        GameData.playerData.adChallengeCount = GameData.GetCurlevelChallengeAdTimes();
        GameData.playerData.turntableFreeTimes = GameData.GetTurnFreeTimes();
        GameData.playerData.turntableVideoTimes = GameData.GetTurnADTimes();
        GameData.playerData.secretShopFreeTimes = GameData.GetSecretShopFreeTimes();
        GameData.playerData.secretShopVideoTimes = GameData.GetSecretShopVideoTimes();
        GameData.playerData.secretShopReward = GameData.GetSecretShopLt();
    }

    static GetNumByType(type: number, add = 0): number {//gunRandomSpend_config 升级消耗备注类型
        switch (type) {
            case 1:
                return GameData.playerData.Gold += add;
            case 3:
                return GameData.playerData.blueStuff += add;
            case 4:
                return GameData.playerData.purpleStuff += add;
            case 5:
                return GameData.playerData.yellowStuff += add;
            case 6:
                return GameData.playerData.redStuff += add;
            case 7:
                return GameData.playerData.pearls += add;
        }
    }

    static DropByType(type: number, porpConfig, pos) {
        switch (type) {
            case 1:
                EvtManger.do(EventName.dropGiftGold, pos);
                break;
            case 2:
                //EvtManger.do(EventName.dropSkin, this.mReward, porpConfig.propNum, this.node.position.add(this.node.parent.position));
                break;
            case 3:
                EvtManger.do(EventName.dropMaterial, porpConfig, pos);
                break;
            case 4:
                EvtManger.do(EventName.dropMaterial, porpConfig, pos);
                break;
            case 5:
                EvtManger.do(EventName.dropMaterial, porpConfig, pos);
                break;
            case 6:
                EvtManger.do(EventName.dropMaterial, porpConfig, pos);
                break;
            case 7:
                EvtManger.do(EventName.dropPearls, porpConfig.propNum, pos);
                break;

        }
    }

}
